#!/bin/bash
# cdwork shell function that wraps ccwork and actually changes directories
#
# Installation:
# Add to your ~/.bashrc or ~/.zshrc:
#   source /path/to/ccwork/cdwork.sh
#
# Usage:
#   cdwork           # List directories (calls ccwork --list-dir)
#   cdwork -l        # List directories (same as above)
#   cdwork -v        # List directories with verbose info
#   cdwork -e ID     # Enter directory by ID and actually cd to it

cdwork() {
    case "$1" in
        -e|--enter)
            if [[ -z "$2" ]]; then
                echo "❌ Missing directory ID. Usage: cdwork -e <ID>"
                return 1
            fi
            
            # Get directory path from ccwork --enter-dir and extract the path
            local output=$(ccwork --enter-dir "$2" 2>&1)
            local dir_path=$(echo "$output" | grep "^cd " | sed "s/^cd '//; s/'$//")
            
            if [[ -n "$dir_path" ]] && [[ -d "$dir_path" ]]; then
                cd "$dir_path"
                echo "📂 $(pwd)"
            else
                # Show the error message from ccwork
                echo "$output"
                return 1
            fi
            ;;
        -l|--list)
            # List directories using ccwork --list-dir, pass through additional args
            shift  # Remove -l from arguments
            # Check for refresh/cache flags and handle them specially
            local has_refresh=false
            local filtered_args=()
            for arg in "$@"; do
                case "$arg" in
                    -r|--refresh|--clear-cache)
                        has_refresh=true
                        ;;
                    *)
                        filtered_args+=("$arg")
                        ;;
                esac
            done
            
            if [[ "$has_refresh" == true ]]; then
                # Clear cache first using the Python cdwork command
                python -c "from ccwork.cli import clear_directory_cache; clear_directory_cache()" 2>/dev/null || true
            fi
            ccwork --list-dir "${filtered_args[@]}"
            ;;
        -v|--verbose)
            # Verbose mode
            ccwork --list-dir --verbose
            ;;
        -lv)
            # Combined list and verbose
            ccwork --list-dir --verbose
            ;;
        -l*)
            # Handle -l combined with other flags like -la, --all
            local args="$1"
            shift
            # Check for refresh/cache flags
            local has_refresh=false
            local filtered_args=()
            for arg in "$@"; do
                case "$arg" in
                    -r|--refresh|--clear-cache)
                        has_refresh=true
                        ;;
                    *)
                        filtered_args+=("$arg")
                        ;;
                esac
            done
            
            # Extract the part after -l and add it to the arguments
            local remaining="${args#-l}"
            local all_args=()
            if [[ -n "$remaining" ]]; then
                all_args+=("$remaining")
            fi
            all_args+=("${filtered_args[@]}")
            
            if [[ "$has_refresh" == true ]]; then
                # Clear cache first
                python -c "from ccwork.cli import clear_directory_cache; clear_directory_cache()" 2>/dev/null || true
            fi
            ccwork --list-dir "${all_args[@]}"
            ;;
        -r|--refresh|--clear-cache)
            # Handle refresh/clear cache flags directly
            shift  # Remove the flag from arguments
            # Clear cache and then list directories
            python -c "from ccwork.cli import clear_directory_cache; clear_directory_cache()" 2>/dev/null || true
            ccwork --list-dir "$@"
            ;;
        "")
            # No arguments - default to filtered list (same as ccwork -d)
            ccwork -d
            ;;
        [0-9]*)
            # Check if it's a number - if so, treat as directory ID
            if [[ "$1" =~ ^[0-9]+$ ]]; then
                # Get directory path from ccwork --enter-dir and extract the path
                local output=$(ccwork --enter-dir "$1" 2>&1)
                local dir_path=$(echo "$output" | grep "^cd " | sed "s/^cd '//; s/'$//")
                
                if [[ -n "$dir_path" ]] && [[ -d "$dir_path" ]]; then
                    cd "$dir_path"
                    echo "📂 $(pwd)"
                else
                    # Show the error message from ccwork
                    echo "$output"
                    return 1
                fi
            else
                # Pass through other arguments to ccwork -d
                ccwork -d "$@"
            fi
            ;;
        /*)
            # Absolute path - try to find matching directory ID and cd to it
            local target_path="$1"
            
            # First try to find the directory by path directly
            if [[ -d "$target_path" ]]; then
                cd "$target_path"
                echo "📂 $(pwd)"
                return 0
            fi
            
            # If direct path doesn't exist, try to find it in the ccwork directory list
            local dir_list_output=$(ccwork --list-dir 2>/dev/null)
            local found_id=""
            
            # Parse the directory list to find matching path
            while IFS= read -r line; do
                # Look for lines that match the pattern "ID. PATH"
                if [[ "$line" =~ ^[[:space:]]*([0-9]+)\.[[:space:]]+(.+)$ ]]; then
                    local id="${BASH_REMATCH[1]}"
                    local dir_path="${BASH_REMATCH[2]}"
                    
                    # Remove any ANSI color codes from the path
                    # Use a simpler approach that works across shells
                    dir_path=$(printf '%s\n' "$dir_path" | sed 's/\x1b\[[0-9;]*m//g' 2>/dev/null || printf '%s\n' "$dir_path")
                    
                    if [[ "$dir_path" == "$target_path" ]]; then
                        found_id="$id"
                        break
                    fi
                fi
            done <<< "$dir_list_output"
            
            if [[ -n "$found_id" ]]; then
                # Found the directory, use the ID to navigate
                local output=$(ccwork --enter-dir "$found_id" 2>&1)
                local dir_path=$(echo "$output" | grep "^cd " | cut -c4- | sed "s/^'//; s/'$//")
                
                if [[ -n "$dir_path" ]] && [[ -d "$dir_path" ]]; then
                    cd "$dir_path"
                    echo "📂 $(pwd)"
                else
                    echo "❌ Error navigating to directory: $target_path"
                    return 1
                fi
            else
                echo "❌ Directory not found in ccwork list: $target_path"
                echo "Use 'cdwork' to see available directories"
                return 1
            fi
            ;;
        *)
            # Pass through other arguments to ccwork -d
            ccwork -d "$@"
            ;;
    esac
}

# Shorter alias if preferred
alias cw='cdwork'

# Optional: Add tab completion for directory IDs
# This is a simple implementation - could be enhanced
_cdwork_completion() {
    local cur prev opts
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    
    if [[ ${prev} == "-e" || ${prev} == "--enter" ]]; then
        # Complete with directory IDs (1-20 should cover most cases)
        COMPREPLY=( $(compgen -W "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20" -- ${cur}) )
        return 0
    fi
    
    opts="-e --enter -l --list -v --verbose -lv"
    COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
}

# Enable tab completion if running in bash
if [[ -n "$BASH_VERSION" ]]; then
    complete -F _cdwork_completion cdwork cw
fi